package com.lu.common.quartz.utils;

import com.lu.common.quartz.domain.ScheduleJob;
import org.mybatis.spring.annotation.MapperScan;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 计划任务管理(增删改查)
 */
@Service
public class QuartzManage {

   @Autowired
   private Scheduler scheduler;

    /**
     * 添加任务
     */
    public void addJob(ScheduleJob job){
        System.out.println("QuartzManage---addJob");
        //创建jobDetail实例，绑定Job实现类
        //指定job名称，所在组的名称，以及绑定job类
        try {
            Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(job.getBeanClass()).newInstance()).getClass();
            //任务名称和组构成任务key
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getJobName(),job.getJobGroup()).build();
            //定义调度触发规则（cronTrigger规则）
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(),job.getJobGroup())//触发key
                    .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
                    .withSchedule(CronScheduleBuilder.cronSchedule(job.getCronExpression())).startNow().build();
            //把作业和触发器注册到任务调度中
            scheduler.scheduleJob(jobDetail,trigger);
            //启动
            if(!scheduler.isShutdown()){
                scheduler.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
